package models

import (
	"database/sql/driver"
	"fmt"
	"git.inedcn.com/ined/cmn"
	"time"
)

type XTime time.Time

func (t XTime) MarshalJSON() ([]byte, error) {
	ti := time.Time(t)
	tune := ti.Format(`"2006-01-02 15:04:05"`)
	return []byte(tune), nil
}

func (t XTime) GetBjTime() time.Time {
	// 将服务器UTC转成北京时间
	uTime := time.Now()
	return uTime.In(time.FixedZone("CST", 8*60*60))
}

// Value insert timestamp into mysql need this function.
func (t XTime) Value() (driver.Value, error) {
	var zeroTime time.Time
	ti := time.Time(t)
	if ti.UnixNano() == zeroTime.UnixNano() {
		return nil, nil
	}
	return ti, nil
}

// Scan valueof time.Time
func (t *XTime) Scan(v interface{}) error {
	ti, ok := v.(time.Time) // NOT directly assertion v.(XTime)
	if ok {
		*t = XTime(ti)
		return nil
	}
	return fmt.Errorf("can not convert %v to timestamp", v)
}

func (t *XTime) String() string {
	fmt.Println(t)
	return t.String()
}

//
//type BaseModel struct {
//  Id        uint   `json:"id" gorm:"primarykey"`
//  CreatedAt XTime  `json:"created_at"`
//  UpdatedAt XTime  `json:"updated_at"`
//  DeletedAt *XTime `json:"-" gorm:"index"`
//}

type BaseModel struct {
	Id        int64        `xorm:"pk autoincr" json:"id"`
	CreatedAt cmn.JsonTime `xorm:"created" json:"created_at"`
	UpdatedAt cmn.JsonTime `xorm:"updated" json:"updated_at"`
	DeletedAt cmn.JsonTime `xorm:"deleted" json:"-"`
}

type DataModel struct {
	IsSuccess bool        `json:"is_success"`
	Data      interface{} `json:"data"`
	Msg       string      `json:"msg"`
}

func (d *DataModel) String() string {
	return fmt.Sprintf("is_success: %t, data: %d, msg: %s", d.IsSuccess, d.Data, d.Msg)
}

type ReqTransfer struct {
	Str string `json:"xml"`
}

type ReqJsonTransfer struct {
	Req interface{} `json:"req"`
}

type DataJsonTransferModel struct {
	IsSuccess bool   `json:"is_success"`
	Data      []byte `json:"data"`
	Msg       string `json:"msg"`
}
